//https://leetcode.cn/problems/spiral-matrix-ii/
package codeRandomThoughts.Test59螺旋矩阵II;

//要认识到不是所有题目都有算法 这是一道模拟题!!!
public class Solution {

    /**
     * 终于写对了 只能说成就感满满
     * @param n
     * @return
     */
    public int[][] generateMatrix(int n) {
        //逆时针一圈就是 往右->往下->往左->往上
        //每到该往上的时候,该方向上的路径长度就会永久减一
        int[][] matrix = new int[n][n];
        matrix[0][0] = 1;
        int total = n * n;
        int i = 0;
        int j = 0;
        int num = 2;
        int length = n - 1;

        //这里肯定要等于 因为最后一个num还要靠循环里面的语句塞进去
        //什么时候把length缩短? 探测到按原来的length会覆盖值的时候
        while (num <= total) {
            int k = 1;
            //往右
            if (matrix[i][j + length] != 0) {
                length--;
            }
            for (k = 1; k <= length; k++) {
                j++;
                matrix[i][j] = num;
                num++;
            }
            if (num > total)
                break;

            //往下
            if (matrix[i + length][j] != 0) {
                length--;
            }
            for (k = 1; k <= length; k++) {
                i++;
                matrix[i][j] = num;
                num++;
            }
            if (num > total)
                break;

            //往左
            if (matrix[i][j - length] != 0) {
                length--;
            }
            for (k = 1; k <= length; k++) {
                j--;
                matrix[i][j] = num;
                num++;
            }
            if (num > total)
                break;

            //往上
            if (matrix[i - length][j] != 0) {
                length--;
            }
            for (k = 1; k <= length; k++) {
                i--;
                matrix[i][j] = num;
                num++;
            }
            if (num > total)
                break;

        }
        return matrix;
    }
}
